package com.cash.app.ui.loan

import android.content.Context
import android.content.Intent
import android.graphics.Paint
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import coil3.load
import coil3.request.placeholder
import com.cash.app.R
import com.cash.app.base.BaseActivity
import com.cash.app.constant.AppConstant.LOAN_CONFIRM_ITEM_SIZE
import com.cash.app.custom.CommonDialog
import com.cash.app.databinding.AcLoanConfirmBinding
import com.cash.app.databinding.DialogLoanConfirmBinding
import com.cash.app.manager.model.VipProductResponse
import com.cash.app.ui.loan.adapter.RecommendListAdapter
import com.cash.app.ui.loan.model.ApplyOrdersRequest
import com.cash.app.ui.loan.model.PrepareResponse
import com.cash.app.ui.loan.model.RecommendDataResponse
import com.cash.app.utils.NumberUtils
import com.cash.app.utils.addVerticalSpacing
import com.cash.app.utils.hide
import com.cash.app.utils.visible

class LoanConfirmActivity : BaseActivity() {

    companion object {
        private const val EXTRA_P_ID = "E_P_ID"
        private const val EXTRA_P_MONEY = "E_P_MONEY"
        private const val EXTRA_P_PERIOD = "E_P_PERIOD"
        private const val EXTRA_P_NAME = "E_P_NAME"
        private const val EXTRA_P_ICON = "E_P_ICON"
        private const val EXTRA_P_VIP = "E_P_VIP"

        fun start(
            context: Context,
            productId: Int,
            productMoney: Int,
            productPeriod: Int,
            productName: String,
            productIcon: String,
            productVip: Boolean = false,
        ) {
            val intent = Intent(context, LoanConfirmActivity::class.java).apply {
                putExtra(EXTRA_P_ID, productId)
                putExtra(EXTRA_P_MONEY, productMoney)
                putExtra(EXTRA_P_PERIOD, productPeriod)
                putExtra(EXTRA_P_NAME, productName)
                putExtra(EXTRA_P_ICON, productIcon)
                putExtra(EXTRA_P_VIP, productVip)
            }
            context.startActivity(intent)
        }
    }

    private lateinit var binding: AcLoanConfirmBinding
    private val viewModel: LoanConfirmACViewModel by viewModels()
    private val recommendAdapter = RecommendListAdapter()
    private var productId = 0;
    private var productMoney = 0
    private var productPeriod = 0
    private var productName = ""
    private var productIcon = ""
    private var productVip = false
    private var showVipDialog = false
    private var vipData: VipProductResponse? = null

    override val isFitsSystemWindows: Boolean
        get() = false

    override val isFitNavigationBarInsets: Boolean
        get() = true

    override val statusBarColor: Int
        get() = R.color.transparent

    override fun setViewBind() {
        binding = AcLoanConfirmBinding.inflate(layoutInflater)
    }

    override fun getLayoutView(): View {
        return binding.root
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setupObservers()
        setupViews()
        initData()
    }

    private fun setupViews() {
        binding.recommendListRv.apply {
            layoutManager = LinearLayoutManager(this@LoanConfirmActivity)
            adapter = recommendAdapter
            addVerticalSpacing(resources.getDimensionPixelSize(R.dimen.loan_confirm_item_spacing))
        }

        binding.btnBorrow.setOnClickListener {
            applyOrder()
        }
    }

    private fun setupObservers() {
        viewModel.prepareData.observe(this) { response ->
            updateProductInfo(response)
        }

        viewModel.recommendData.observe(this) { response ->
            if (response.list.isEmpty()) {
                binding.loanRecommendCl.visibility = View.GONE
                binding.recommendTipLl.visibility = View.GONE
            } else {
                binding.loanRecommendCl.visibility = View.VISIBLE
                binding.recommendTipLl.visibility = View.VISIBLE
                recommendAdapter.setData(response.list)
            }
        }

        viewModel.applyOrdersData.observe(this) { response ->
            LoanConfirmResultActivity.start(this, response.remark)
            finish()
        }

        viewModel.vipProduct.observe(this) { rsp ->
            showVipDialog = rsp.show_special
            vipData = rsp
            if (rsp.show_special) {
//                // mock data
//                val gson = Gson()
//                val rsp = gson.fromJson(
//                    "{\n" + "  \"show_special\": true,\n" + "  \"pop_title\": \"VIP Products\",\n" + "  \"pop_desc\": \"Better than good,Better than good,Better than good,Better than good!\",\n" + "  \"pop_btn_title\": \"Apply Now\",\n" + "  \"p_id\": 1,\n" + "  \"p_name\": \"product1\",\n" + "  \"p_icon\": \"https://download.menggaliuang.io/picture/20231201/c123b7e0ba24041d643099dde98073a0.png\",\n" + "  \"p_money\": 300000,\n" + "  \"p_peroid\": 6,\n" + "  \"p_receive_amount\": 270000,\n" + "  \"p_common_receive_amount\": 210000\n" + "}",
//                    VipProductResponse::class.java
//                )
//                showVipDialog(rsp)
            }
        }
    }

    private fun initData() {
        productId = intent.getIntExtra(EXTRA_P_ID, -1)
        productMoney = intent.getIntExtra(EXTRA_P_MONEY, -1)
        productPeriod = intent.getIntExtra(EXTRA_P_PERIOD, -1)
        productName = intent.getStringExtra(EXTRA_P_NAME) ?: ""
        productIcon = intent.getStringExtra(EXTRA_P_ICON) ?: ""
        productVip = intent.getBooleanExtra(EXTRA_P_VIP, false)

        if (productName.isNotEmpty() && productId != -1) {
            getProductInfo(productId, productMoney, productPeriod)
        } else {
            Toast.makeText(
                this, getString(R.string.loan_confirm_params_error), Toast.LENGTH_SHORT
            ).show()
        }

    }

    private fun getProductInfo(pId: Int, pMoney: Int, pPeriod: Int) {
        viewModel.getPrepareData(pId, pMoney, pPeriod)
        viewModel.getRecommendData(pId)
        if (!productVip) {
            viewModel.getVipProduct()
        }
    }

    private fun updateProductInfo(prepareData: PrepareResponse) {
        with(binding) {
            tvProductName.text = productName
            if (productIcon.isNotEmpty()) {
                ivProductIcon.load(productIcon) {
                    placeholder(R.mipmap.app_icon)
                }
            }
            tvAmount.text = NumberUtils.toRupeeWithComma(productMoney)
            tvInterestFee.text = getString(
                R.string.unit_rupee_prefix,
                NumberUtils.toRupeeWithComma(prepareData.r_interest_money)
            )
            tvServiceFee.text = getString(
                R.string.unit_rupee_prefix,
                NumberUtils.toRupeeWithComma(prepareData.r_service_money)
            )
            tvRepaymentAmount.text = getString(
                R.string.unit_rupee_prefix, NumberUtils.toRupeeWithComma(prepareData.r_total_money)
            )
            tvAmountReceived.text = getString(
                R.string.unit_rupee_prefix,
                NumberUtils.toRupeeWithComma(prepareData.r_receive_money)
            )
            tvLoanTenure.text = getString(R.string.unit_tenure, productPeriod.toString())
            tvGstFee.text = getString(
                R.string.unit_rupee_prefix, NumberUtils.toRupeeWithComma(prepareData.gst_fee)
            )
            if (prepareData.gst_rate.isNotEmpty()) {
                tvGstRateLabel.visible()
                tvGstRateLabel.text = getString(
                    R.string.gst_rate, prepareData.gst_rate
                )
            } else {
                tvGstRateLabel.hide()
            }
            tvDueDate.text = prepareData.due_time_string
        }
    }

    private fun applyOrder() {
        val sRecommendList = recommendAdapter.getSelectedProducts()
        if (sRecommendList.isEmpty()) {
            Toast.makeText(
                this, getString(R.string.loan_confirm_select_one), Toast.LENGTH_SHORT
            ).show()
            return
        }
        val applyProductList = mutableListOf<ApplyOrdersRequest.Product>()

        // add mainProduct
        val mainProduct = ApplyOrdersRequest.Product(productId, productMoney, productPeriod)
        applyProductList.add(mainProduct)

        // Add selected recommended products
        sRecommendList.forEach { rProduct ->
            applyProductList.add(
                ApplyOrdersRequest.Product(
                    rProduct.p_id, rProduct.p_money, rProduct.p_peroid
                )
            )
        }

        if (sRecommendList.size >= LOAN_CONFIRM_ITEM_SIZE) {
            showConfirmDialog(sRecommendList) {
                viewModel.applyOrder(applyProductList)
            }
        } else {
            viewModel.applyOrder(applyProductList)
        }
    }

    private fun showConfirmDialog(
        selectedProducts: List<RecommendDataResponse.Product>, onConfirm: () -> Unit
    ) {
        val dialogBinding = DialogLoanConfirmBinding.inflate(layoutInflater)
        // Calculate total credit
        var totalCredit = 0
        var allName = ""
        selectedProducts.forEach {
            allName = allName + it.p_name + "\n"
            totalCredit += it.p_money
        }
        with(dialogBinding) {
            productsName.text = allName
            tvProductsCount.text = selectedProducts.size.toString()
            tvTotalCredit.text = NumberUtils.toRupeeWithComma(totalCredit)
        }

        CommonDialog.Builder(this).apply {
            showTitle(true)
            setTitle(getString(R.string.loan_confirm))
            setContentView(dialogBinding.root)
            showButtons(true)
            addButton(getString(R.string.cancel), { dialog ->
                dialog.dismiss()
            })
            addButton(getString(R.string.loan_confirm), { dialog ->
                onConfirm.invoke()
            }, R.color.yellow_4)
            setCancelable(true)
            setCancelableOnTouchOutside(true)
        }.build().show()
    }


    private fun showVipDialog(vipProduct: VipProductResponse) {
        binding.apply {
            vipDialogCl.visible()
            vipDialogCl.setOnClickListener {}
            vipTitle.text = vipProduct.pop_title
            vipBtn.text = vipProduct.pop_btn_title
            vipContentView.vipTip.text = vipProduct.pop_desc
            vipBtn.setOnClickListener {
//                val applyProductList = mutableListOf<ApplyOrdersRequest.Product>()
//                val item = ApplyOrdersRequest.Product(
//                    vipProduct.p_id, vipProduct.p_money, vipProduct.p_peroid
//                )
//                applyProductList.add(item)
//                viewModel.applyOrder(applyProductList)
                productId = vipProduct.p_id
                productMoney = vipProduct.p_money
                productPeriod = vipProduct.p_peroid
                productName = vipProduct.p_name
                productIcon = vipProduct.p_icon
                productVip = true

                getProductInfo(vipProduct.p_id, vipProduct.p_money, vipProduct.p_peroid)

                vipDialogCl.hide()
                dialogShow = false
                count = 0
            }
            if (vipProduct.p_icon.isNotEmpty()) {
                vipContentView.vipIcon.load(vipProduct.p_icon) {
                    placeholder(R.mipmap.app_icon)
                }
            }
            vipContentView.vipProductName.text = vipProduct.p_name
            vipContentView.productMoney.text = NumberUtils.toRupeeWithComma(vipProduct.p_money)
            vipContentView.productReceiveMoney.text =
                NumberUtils.toRupeeWithComma(vipProduct.p_receive_amount)
            vipContentView.productCommonReceiveMoney.text =
                NumberUtils.toRupeeWithComma(vipProduct.p_common_receive_amount)
            vipContentView.productCommonReceiveMoney.paintFlags =
                vipContentView.productCommonReceiveMoney.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG

        }
        dialogShow = true
    }

    private var dialogShow: Boolean = false
    private var count = 0

    override fun onBackPressed() {
        if (dialogShow) {
            if (count == 1) {
                binding.vipDialogCl.hide()
                count = 0
                finish()
            } else {
                count++
            }
        } else {
            if (showVipDialog) {
                vipData?.let {
                    showVipDialog(it)
                    showVipDialog = false
                }
            } else {
                super.onBackPressed()
            }
        }
    }
} 